import {
    AbstractBookCrawler,
    BasicBook,
    BasicChapter,
    Book,
    request,
    SearchBookResult,
    BookCrawlerTest,
    BookSource
} from '../../common/common_node.js'

class BookCrawler extends AbstractBookCrawler {

    chooseString(firstString, secondString) {
        return firstString ? firstString : secondString;
    }

    async searchBook(keyword, pageNum) {


        const url = this.source.searchBaseUrl + '?k=' + keyword + "&page=" + pageNum;
        const $ = await (await request(url)).doc();
        const fictionList = $(".fiction-list");
        const bookArr = [];
        const that = this;
        fictionList.each(function (i, e) {
            const name = $(e).find(".title a").text().trim();
            const path = $(e).find(".title a").attr("href");
            const author = that.chooseString($(this).find(".author a").text().trim(), undefined);
            bookArr.push(new BasicBook({
                name, author, path
            }));
        })

        // 获取所有的页码链接
        const pageLinks = $(".pager a");
        let pages = 1; // 默认设置为1
        pageLinks.each(function (i, e) {
            const href = $(e).attr("href");
            if (!href) {
                return;
            }
            // 使用正则表达式从href中提取页码
            const regex = /page=(\d+)/;
            const match = href.match(regex);
            if (match) {
                pages = Math.max(pages, parseInt(match[1], 10));
            }
        });

        return new SearchBookResult({
            pageNum: pageNum,
            pages: pages,
            keyword: keyword,
            bookList: bookArr
        });
    }

    async bookDetails(path) {

        const $ = await (await request(this.source.bookBaseUrl + path)).doc();

        const brief = $(".brief");

        let intro;
        if (brief.length === 0) {
            intro = $(".content p").first().text();
        } else {
            intro = brief.text().trim().replace("导读：", "");
        }

        return new Book({
            name: $(".title").text().trim(),
            author: this.chooseString($(".author a").text().trim(), undefined),
            path: path,
            intro: intro,
            coverUrl: null,
            type: null
        });
    }

    async bookCatalog(path) {

        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        const chapters = $('.chapters a');
        if (chapters.length === 0) {
            return [{
                index: 0,
                title: $(".title").text().trim(),
                path: path
            }];
        } else {
            let catalog = [];
            chapters.each(function (i, e) {
                const item = $(e);
                catalog.push(new BasicChapter({
                    index: i,
                    title: item.text(),
                    path: item.attr("href")
                }));
            });
            return catalog;
        }
    }

    async chapterContent(path) {
        const $ = await (await request(this.source.bookBaseUrl + path)).doc();
        const pArr = $(".content p");
        let content = "";
        pArr.each(function (i, e) {
            content += $(e).text() + '\n\n';
        });
        return content;
    }
}

const source = {
    "id": "cnbook/1",
    "name": "xbook",
    "portalUrl": "https://xbookcn.org",
    "searchBaseUrl": "https://xbookcn.org",
    "bookBaseUrl": "https://xbookcn.org",
    "active": true
};

await new BookCrawlerTest(new BookCrawler(BookSource.createTestBookSource(source)), {
    enableSearch: true,
    keyword: "迷踪奸影",
}).run();

